package com.jimmyhsu.ecnudaowei.coursetable.checkin;

import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.CardView;
import android.support.v7.widget.Toolbar;
import android.util.Log;
import android.view.MenuItem;
import android.view.View;
import android.widget.Toast;

import com.amap.api.location.AMapLocation;
import com.amap.api.location.AMapLocationClient;
import com.amap.api.location.AMapLocationClientOption;
import com.amap.api.location.AMapLocationListener;
import com.amap.api.maps.AMapUtils;
import com.amap.api.maps.model.LatLng;
import com.jimmyhsu.ecnudaowei.MyApplication;
import com.jimmyhsu.ecnudaowei.R;
import com.jimmyhsu.ecnudaowei.login.LoginActivity;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
import retrofit2.Retrofit;
import retrofit2.converter.gson.GsonConverterFactory;
import retrofit2.converter.scalars.ScalarsConverterFactory;

/**
 * Created by jimmyhsu on 2017/3/29.
 */

public class CheckInActivity extends AppCompatActivity implements AMapLocationListener {

    public static final String TAG = "CheckInActivity";
    public static final int REQUEST_BARCODE = 1;
    private static final String EXTRA_COURSE_ID = "extra_course_id";

    private String mCourseId;
    @BindView(R.id.id_ci_qrcode)
    CardView mQrcodeView;
    @BindView(R.id.id_ci_toolbar)
    Toolbar mToolbar;

    private ProgressDialog mProgressDialog;

    private CheckInType mRequirements;
    private String mToken = null;

    private AMapLocationClient mLocationClient = null;
    private AMapLocationClientOption mLocationOption = null;
    private int mGetLocationAttemptCount = 0;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_check_in);
        ButterKnife.bind(this);
        setSupportActionBar(mToolbar);
        getSupportActionBar().setDisplayHomeAsUpEnabled(true);
        mToolbar.setNavigationOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });
        mCourseId = getIntent().getStringExtra(EXTRA_COURSE_ID);
        setTitle("");
    }

    @OnClick(R.id.id_ci_qrcode)
    void qrCodeCheckIn() {
        Intent intent = new Intent(this, MipcaActivityCapture.class);
        startActivityForResult(intent, REQUEST_BARCODE);
    }

    @OnClick(R.id.id_ci_regular)
    void photoCheckIn() {
        CameraCheckInActivity.startActivity(this, mCourseId);
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        if (item.getItemId() == android.R.id.home) {
            finish();
            return true;
        }
        return super.onOptionsItemSelected(item);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == REQUEST_BARCODE && resultCode == RESULT_OK) {
            String scanedCode = data.getStringExtra(MipcaActivityCapture.EXTRA_MESSAGE);
            checkIn(scanedCode);
        }
    }

    private void checkIn(String scanedCode) {
        mProgressDialog = new ProgressDialog(this);
        mProgressDialog.setIndeterminate(true);
        mProgressDialog.setMessage("签到中，请勿退出...");
        mProgressDialog.setCancelable(false);
        mProgressDialog.show();
        Retrofit retrofit = new Retrofit.Builder()
                .baseUrl(LoginActivity.BASE_URL)
                .addConverterFactory(GsonConverterFactory.create())
                .addConverterFactory(ScalarsConverterFactory.create())
                .build();
        QrcodeUploadService service = retrofit.create(QrcodeUploadService.class);
        Call<CheckInType> call = service.getCheckInRequirements(MyApplication.getInstance(this).getName(),
                scanedCode);
        call.enqueue(new Callback<CheckInType>() {
            @Override
            public void onResponse(Call<CheckInType> call, Response<CheckInType> response) {
                mRequirements = response.body();
                if (mRequirements != null && mRequirements.getStatus() == 0) {
                    checkRequirements(mRequirements);
                } else {
                    Toast.makeText(CheckInActivity.this, "该二维码不能签到", Toast.LENGTH_SHORT).show();
                }
            }

            @Override
            public void onFailure(Call<CheckInType> call, Throwable t) {
                mProgressDialog.hide();
                Toast.makeText(CheckInActivity.this, "与服务器连接失败", Toast.LENGTH_SHORT).show();
            }
        });
    }

    private void checkRequirements(CheckInType requirements) {
//        Log.e(TAG, "courseId = " + requirements.getCourseId() + "longtitude = " + requirements.getLongtitude() + ", latitude = " + requirements.getLatitude() + ", range = " + requirements.getValidRange());
        if (!requirements.getCourseId().equals(mCourseId)) {
            mProgressDialog.hide();
            Toast.makeText(this, "签到失败-课程不匹配", Toast.LENGTH_SHORT).show();
        } else {
            mToken = requirements.getToken();
            if (mLocationClient == null) {
                mLocationClient = new AMapLocationClient(getApplicationContext());
                mLocationClient.setLocationListener(this);
                mLocationOption = new AMapLocationClientOption();
                mLocationOption.setLocationMode(AMapLocationClientOption.AMapLocationMode.Hight_Accuracy);
                mLocationOption.setInterval(1000);
                mLocationOption.setNeedAddress(false);
                mLocationOption.setHttpTimeOut(10000);
                mLocationClient.setLocationOption(mLocationOption);
            }
            mGetLocationAttemptCount = 0;
            mLocationClient.startLocation();

        }
    }

    public static void startActivity(Context context, String courseId) {
        Intent intent = new Intent(context, CheckInActivity.class);
        intent.putExtra(EXTRA_COURSE_ID, courseId);
        context.startActivity(intent);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (mLocationClient != null) {
            mLocationClient.onDestroy();
        }
    }

    @Override
    public void onLocationChanged(AMapLocation amapLocation) {
        if (amapLocation != null) {
            if (amapLocation.getErrorCode() == 0) {
                //可在其中解析amapLocation获取相应内容。
                double latitude = amapLocation.getLatitude();
                double longtitude = amapLocation.getLongitude();
                float accuracy = 200;
                LatLng myLatlng = new LatLng(latitude, longtitude);
                LatLng crsLatlng = new LatLng(mRequirements.getLatitude(), mRequirements.getLongtitude());
                float distance = AMapUtils.calculateLineDistance(myLatlng, crsLatlng);
//                Log.e("haha", "lat: " + myLatlng.latitude + ", " + "lon: " + myLatlng.longitude + ", src: " + crsLatlng.latitude + ", " + crsLatlng.longitude);
//                Log.e("haha", "dis: " + distance + ", acc: " + accuracy);
                if (distance <= accuracy) {
                    mLocationClient.stopLocation();
                    uploadCheckInSuccessMessage();
                }
            } else {
                //详见amap错误码表。
                Log.e("AmapError", "location Error, ErrCode:"
                        + amapLocation.getErrorCode() + ", errInfo:"
                        + amapLocation.getErrorInfo());
            }
            mGetLocationAttemptCount++;
            if (mGetLocationAttemptCount >= 10) {
                mProgressDialog.hide();
                Toast.makeText(this, "签到失败-建议打开wifi和gps定位，手机必须处于上课教学楼内", Toast.LENGTH_SHORT).show();
                mLocationClient.stopLocation();
            }
        }
    }

    private void uploadCheckInSuccessMessage() {
        Retrofit retrofit = new Retrofit.Builder()
                .baseUrl(LoginActivity.BASE_URL)
                .addConverterFactory(ScalarsConverterFactory.create())
                .build();
//        Log.e(TAG, "token uploading");
        CheckInSuccessUploadService service = retrofit.create(CheckInSuccessUploadService.class);
        MyApplication app = MyApplication.getInstance(this);
//        Log.e(TAG, app.getName() +", " + app.getPassword() + ", " + mToken);
        Call<String> call = service.uploadCheckInSuccess(app.getName(), app.getPassword(), mToken);
        call.enqueue(new Callback<String>() {
            @Override
            public void onResponse(Call<String> call, Response<String> response) {
                mProgressDialog.hide();
//                Log.e(TAG, "token uploaded: " + response.body());
                if (response.body().equals("success")) {
                    Toast.makeText(CheckInActivity.this, "签到成功！", Toast.LENGTH_SHORT).show();
                    CheckInActivity.this.finish();
                } else if (response.body().equals("err1")) {
                    Toast.makeText(CheckInActivity.this, "今日已经签过到", Toast.LENGTH_SHORT).show();
                } else if (response.body().equals("err2")) {
                    Toast.makeText(CheckInActivity.this, "签到失败-令牌过期", Toast.LENGTH_SHORT).show();
                } else {
                    Toast.makeText(CheckInActivity.this, "服务器异常！", Toast.LENGTH_SHORT).show();
                }
            }

            @Override
            public void onFailure(Call<String> call, Throwable t) {
                mProgressDialog.hide();
                Toast.makeText(CheckInActivity.this, "请检查网络！", Toast.LENGTH_SHORT).show();
            }
        });
    }
}
